/**
 * 
 */
package org.compiere.report;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.logging.Level;

import org.adempiere.exceptions.AdempiereException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBSCAction;
import org.compiere.model.MBSCActionAdditional;
import org.compiere.model.MBSCNetWorkDiag;
import org.compiere.model.MBSCNetWorkDiagLine;
import org.compiere.model.MBSCNetWorkDiagSubLine;
import org.compiere.model.MBSCResponsibleExecutor;
import org.compiere.model.MBSCTargetIndicator;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.process.SvrProcess;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

import extend.org.compiere.utils.Util;

/**
 * @author A.Kulantayev
 *
 */
public class BSC_NetWorkDiag_PrintForm extends SvrProcess {
	//BSC_NetWorkDiag_PrintForm
	/** Current context */
	private Properties m_ctx;
	private ProcessInfo pi;
	/**Current Record_ID */
	int p_BSC_NetWorkDiag_ID = 0;
	/**Out file */
	String ResultPath;
	@Override
	protected void prepare() {
		log.info("");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();
		p_BSC_NetWorkDiag_ID = pi.getRecord_ID();
		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++) {
			String name = para[i].getParameterName();
			if (para[i].getParameter() == null)
				;
			else if (name.equals("BSC_NetWorkDiag_ID")) {
				p_BSC_NetWorkDiag_ID = ((BigDecimal) para[i].getParameter()).intValue();
			}
			else
				log.log(Level.SEVERE, "Unknown Parameter: " + name);
		}
		if(p_BSC_NetWorkDiag_ID==0){
			log.log(Level.SEVERE, "Error initializing the parameter BSC_NetWorkDiag_ID: p_BSC_NetWorkDiag_ID ="+p_BSC_NetWorkDiag_ID);
			throw new AdempiereException(Msg.translate(m_ctx,"Error initializing the parameter BSC_NetWorkDiag_ID. Parameter does not exists"));
		}
	}
	@Override
	protected String doIt() throws Exception {
		MBSCNetWorkDiag netWorkDiag = new MBSCNetWorkDiag(m_ctx, p_BSC_NetWorkDiag_ID, get_TrxName());
		//File path
		ResultPath = Util.getResultPath("Сетевой_график_№ "+netWorkDiag.getDocumentNo(), (new String("Сетевой_график_№ "+netWorkDiag.getDocumentNo()).length())+1);
		// 
		  MAttachmentEntry entry = Util. getAttachment(pi, m_ctx, ResultPath);
		if (entry == null)
			throw new AdempiereException(Msg.translate(m_ctx,"NotFoundTemplate"));
		
		XSSFWorkbook wb = new XSSFWorkbook(entry.getInputStream());
		XSSFSheet sheet = wb.getSheetAt(0);
		Row R = null;
		//Title
		sheet.getRow(5).getCell(0).setCellValue(netWorkDiag.getName().substring(0, 14)+"\n"
				+netWorkDiag.getName().substring(15, 88)+"\n"
				+netWorkDiag.getName().substring(89, 180)+"\n"
				+netWorkDiag.getName().substring(181, netWorkDiag.getName().length()));
		sheet.getRow(5).setHeight((short)(sheet.getRow(5).getHeight()*3));
		//
		int nn = 1;
		int rowNo = 9;
		for(MBSCNetWorkDiagLine netWorkDiagLine : netWorkDiag.getLines(false))
		{
			R = sheet.createRow(rowNo);
			for(int i = 0; i<14; i++){
				R.createCell(i);
				R.getCell(i).setCellStyle(sheet.getRow(0).getCell(4).getCellStyle());
			}
			sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 1, 13));
			R.getCell(1).setCellValue(netWorkDiagLine.getName());
			rowNo++;
			//
			for(MBSCNetWorkDiagSubLine netWorkDiagSubLine : netWorkDiagLine.getSubLines(false))
			{
				//
				if(netWorkDiagSubLine.getName()!=null)
				{
					R = sheet.createRow(rowNo);
					for(int i = 0; i<14; i++){
						R.createCell(i);
						R.getCell(i).setCellStyle(sheet.getRow(0).getCell(4).getCellStyle());
					}
					sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 1, 13));
					R.getCell(1).setCellValue(netWorkDiagSubLine.getName());
					rowNo++;
				}
				
				R = sheet.createRow(rowNo);
				for(int i = 0; i<14; i++){
					R.createCell(i);
					R.getCell(i).setCellStyle(sheet.getRow(0).getCell(4).getCellStyle());
				}
				//Target indicators
				String target_indicators = "Задача: "+netWorkDiagSubLine.getName2()+"\n";
				int target_indicatorsCount = 0;
				for(MBSCTargetIndicator targetIndicator : netWorkDiagSubLine.getTarget_Indicator(false))
				{
					if(target_indicatorsCount==0)
						target_indicators = target_indicators + "Целевые индикаторы:\n";
					target_indicators = target_indicators + targetIndicator.getName()+"\n";
					target_indicatorsCount++;
				}
				//
				sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 1, 13));
				R.getCell(1).setCellValue(target_indicators);
				R.setHeight((short) (sheet.getRow(0).getHeight()*(short)(target_indicatorsCount+3)));
				rowNo++;
				//
				
				//
				for(MBSCAction mbscAction : netWorkDiagSubLine.getActions(false))
				{
					R = sheet.createRow(rowNo);
					for(int i = 0; i<14; i++){
						R.createCell(i);
						R.getCell(i).setCellStyle(sheet.getRow(0).getCell(3).getCellStyle());
					}
					R.getCell(0).setCellValue(String.valueOf(nn));
					R.getCell(0).setCellStyle(sheet.getRow(0).getCell(1).getCellStyle());
					R.getCell(1).setCellValue(mbscAction.getSequence().intValue());
					R.getCell(1).setCellStyle(sheet.getRow(0).getCell(1).getCellStyle());
					
					sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 2, 4));
					R.getCell(2).setCellValue(mbscAction.getName());
					int actionNameLenght = mbscAction.getName().length();
					int hCount = 0;
					int diff = actionNameLenght/30;
					hCount = diff;
					if(actionNameLenght - 30*diff > 0)
						hCount = hCount+2;
					R.setHeight((short) (sheet.getRow(0).getHeight()*hCount));
					
					R.getCell(5).setCellValue(mbscAction.getCompletionForm());
					
					R.getCell(6).setCellValue(mbscAction.getExecutive());
					sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 6, 7));
					//Вот здесь и смотрим распределено ли мероприятие
					
					String periodList = "";
					String amountList = "";
					String budgetprogramList = "";
					String tempPeriod = "";
					if(mbscAction.isDistributed())
					{
						int d = 0;
						 for(MBSCActionAdditional mbscActionAdditional:mbscAction.getActionAdditionals(false))
						 {	
							 //-->Собираем по частям periodList
							 tempPeriod = DB.getSQLValueString(get_TrxName(), "SELECT erps_periodrange(datefrom,dateto) " +
						 				"FROM BSC_ActionAdditional WHERE BSC_ActionAdditional_ID = ?"
						 				, mbscActionAdditional.getBSC_ActionAdditional_ID());
							 
							 if(d!=0)
								 periodList = periodList + ", "; 							 
							 
							 periodList = periodList + tempPeriod;
							 //<--
							 
							 //-->Собираем финансирование
							 if(d!=0)
								 amountList = amountList + ", ";
							 if(mbscActionAdditional.getAmount().intValue() == 0)
								 amountList = amountList+tempPeriod +" - " + "Финансирование не требуется";
							 else
								 amountList = amountList+tempPeriod + " - " +DecimalFormat.getInstance().format(mbscActionAdditional.getAmount().intValue());
							 //<--
							 
							 //-->Собираем код бюджетной программы
							 if(mbscActionAdditional.getCodeBudgetProgramm()!=null)
							 {
//								 if(d!=0)
//									 budgetprogramList = budgetprogramList + ", ";
//								 budgetprogramList = budgetprogramList + tempPeriod+ " - " +mbscActionAdditional.getCodeBudgetProgramm();
								 budgetprogramList = mbscActionAdditional.getCodeBudgetProgramm();
							 }
							 //<--
							 
							 d++;
						 }
						 //-->Обрабатываем то что у нас получилось(Постпроверка)
						 boolean counter = false;
						 for(MBSCActionAdditional actionAdditional:mbscAction.getActionAdditionals(false))
						 {
							 if(actionAdditional.getAmount().intValue() != 0)
								 counter = true;
						 }
						 if(!counter)
							 amountList = "Финансирование не требуется";
						 if(mbscAction.getOtherAmount()!=null)
							 amountList = mbscAction.getOtherAmount();
						 //<--
						 R.getCell(8).setCellValue(periodList);
						 sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 9, 10));
						 
						 R.getCell(9).setCellValue(amountList);
						 
						 R.getCell(11).setCellValue(budgetprogramList);
					}
					else
					{
						//-->Сроки исполнения
						periodList = DB.getSQLValueString(get_TrxName()
								, "SELECT erps_periodrange(datefrom,dateto) FROM BSC_Action WHERE BSC_Action_ID = ?"
								, mbscAction.getBSC_Action_ID());
						
						R.getCell(8).setCellValue(periodList);
						sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 9, 10));
						//<--
						
						//-->Необход. объемы финанси-рования (тыс. тенге)
						if(mbscAction.getAmount().intValue()==0){
							if(mbscAction.getOtherAmount()!=null)
								R.getCell(9).setCellValue(mbscAction.getOtherAmount());
							else
								R.getCell(9).setCellValue("Финансирование не требуется");
						}
						else{
							tempPeriod = new SimpleDateFormat("yyyy").format(mbscAction.getDateFrom())+" год - ";
							//R.getCell(9).setCellStyle(sheet.getRow(0).getCell(5).getCellStyle());
							R.getCell(9).setCellValue(tempPeriod + DecimalFormat.getInstance().format(mbscAction.getAmount().intValue()));
						}
						//<--
						
						//-->Код бюд-жетной программы
						budgetprogramList = mbscAction.getCodeBudgetProgramm();
						R.getCell(11).setCellValue(budgetprogramList);
						//<--	
					}
					//-->Ответст. исполнит. Холдинга и его ДЗО
					String executorsList="";
					int e=0;
					for(MBSCResponsibleExecutor executor : mbscAction.getResponsible_Executors(false))
					{
						if(e!=0)
							executorsList = executorsList+", ";
						//если ДЗО
						if(executor.getName()!=null)
						{
							executorsList = executorsList + executor.getName();
						}
						else{
							executorsList = executorsList+(executor.getAD_User().getC_BPartner().getName()==null?
										executor.getAD_User().getDescription():executor.getAD_User().getC_BPartner().getName());
						}
						//
						e++;
					}
					sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 12, 13));
					R.getCell(12).setCellValue(executorsList);
					//<--
					rowNo++; nn++;
				}
			}
		}
		//delete temp styles
		R = sheet.getRow(0);
		for(int r=0;r<6;r++)
			R.getCell(r).setCellStyle(R.getCell(12).getCellStyle());
		//
		// Write the output to a file
		FileOutputStream fileOut = new FileOutputStream(ResultPath);
		wb.write(fileOut);
		fileOut.close();
		// Open the file with the application associated
		Util.launchFile(new File(ResultPath));	
		return Msg.translate(m_ctx, "Success");
	}
	
}
